<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/31
 * Time: 14:10
 */
namespace Asf\Foundation;

class WebScoketServer
{
    protected $server;

    protected $address;

    protected $port;

    public function __construct($address, $port)
    {
        $this->address = $address;
        $this->port = $port;
        $this->server = new \Swoole\WebSocket\Server($this->address, $this->port);
    }

    public function onOpen(callable $callback)
    {
        $this->server->on('open', function ($server, $request) use($callback) {
            call_user_func_array($callback, [$server, $request]);
        });
    }

    public function onMessage(callable $callback)
    {
        $this->server->on('Message', function ($server, $frame) use($callback) {
            call_user_func_array($callback, [$server, $frame]);
        });
    }

    public function onClose(callable $callback)
    {
        $this->server->on('Close', function ($server, $fd) use($callback) {
            call_user_func_array($callback, [$server, $fd]);
        });
    }

    public function on($event, $callback)
    {
        $this->server->on($event, $callback);
    }

    public function run()
    {
        $this->server->start();
    }
}